var addr = "ws://127.0.0.1:5010"
$(document).ready(function(){
    initGWSocket()
});
function initGWSocket() {
    window.gws = new WebSocket(addr)
    gws.onopen = function() {
        console.log(addr+" 链接成功")
        wsSend(100,null)
    }
    gws.onmessage = function (event){
        var reader = new FileReader();
        reader.readAsArrayBuffer(event.data);
        reader.onload = function (e) {
            var buffer = reader.result
            var dview= new DataView(buffer);
            buffer = buffer.slice(2,buffer.byteLength)
            var cmd = dview.getInt16(0)
            console.log(cmd)
            var blob = new Blob([buffer])
            var reader1 = new FileReader();
            reader1.readAsText(blob)
            reader1.onload = function (e) {
                var obj = JSON.parse(reader1.result)
                console.log(obj)
            }
        }
    }
}
function wsSend(cmd,data) {
    var blob = new Blob([JSON.stringify(data)],{type:"text/plain"});
    //将Blob 对象转换成 ArrayBuffer
    var reader = new FileReader();
    reader.readAsArrayBuffer(blob);
    reader.onload = function (e) {
        var buffer = reader.result
        var buint8 = new Uint8Array(buffer)
        var dview= new DataView(new ArrayBuffer(buint8.byteLength+2));
        dview.setUint16(0,cmd)
        for (var i=0;i<buint8.byteLength;i++){
            dview.setInt8(i+2,buint8[i])
        }
        gws.send(dview.buffer)
    }
}




